import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class TcpClient {
    private Socket socket = null;
    public TcpClient(String IP,int Port) throws IOException {
        socket = new Socket(IP,Port);
        //socket.connect(new InetSocketAddress(InetAddress.getByName(IP),Port));
    }
    public void start(){
        System.out.println("客户端启动");
        //创建输入流和输出流分别用来读取和输出数据
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            System.out.println("->");
            //输入要发送给服务器的数据
            Scanner scanner = new Scanner(System.in);
            //用于获取数据和输出数据
            Scanner newScanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true){
                //读取输入内容
                String request = scanner.next();
                //发送数据
                writer.println(request);
                //缓存区冲刷
                writer.flush();
                //检查从服务器接收的数据流是否还有下一个数据项
                if (!newScanner.hasNext()){
                    break;
                }
                //将数据转化为字符串类型
                String response = newScanner.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient client = new TcpClient("127.0.0.1",2020);
        client.start();
    }
}
